<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="缺陷名称" prop="defectName">
        <el-input v-model="queryParams.defectName" placeholder="请输入缺陷名称" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>

      <!-- <el-form-item label="缺陷类型" prop="parentId">
        <treeselect :searchable="false" 
          v-model="form.parentId"
          :options="deptOptions"
          appendToBody
          :normalizer="normalizer"
          placeholder="选择上级部门"
        />
      </el-form-item> -->
      <el-form-item label="缺陷状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择缺陷状态" clearable size="small">
          <el-option v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['basic:defecttype:add']">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['basic:defecttype:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['basic:defecttype:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['basic:defecttype:export']"
          >导出</el-button
        >
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="defecttypeList" row-key="defectId" default-expand-all :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
      <el-table-column label="缺陷名称" align="center" prop="defectName" width="260" />
      <el-table-column label="显示顺序" align="center" prop="orderNum" />

      <el-table-column label="缺陷状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <!-- <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="200"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['basic:defecttype:edit']">修改</el-button>
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['basic:defecttype:add']"
            >新增</el-button
          > -->
          <el-button v-if="scope.row.parentId != 0" size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['basic:defecttype:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改缺陷类型对话框 -->
    <el-dialog v-myFullscreen :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-row>
          <el-col :span="24" v-if="form.parentId !== 0">
            <el-form-item label="上级缺陷" prop="parentId">
              <!-- <el-input
                v-model="form.parentId"
                placeholder="请输入父缺陷id"
                :disabled="openDisabled"
              /> -->
              <treeselect :searchable="false" v-model="form.parentId" :options="deptOptions" :normalizer="normalizer" placeholder="选择上级部门" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="缺陷名称" prop="defectName">
              <el-input v-model="form.defectName" placeholder="请输入缺陷名称" :disabled="openDisabled" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示顺序" prop="orderNum">
              <el-input-number v-model="form.orderNum" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="缺陷状态">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictValue">{{ dict.dictLabel }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="!openDisabled">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listDefecttype,
  getDefecttype,
  delDefecttype,
  addDefecttype,
  updateDefecttype,
  listDefectExcludeChild,
  changeDefectStatus,
  listInfo,
} from "@/api/basic/defecttype/defecttype";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Defecttype",
  components: { Treeselect },
  data() {
    return {
      //弹窗是否禁止编辑
      openDisabled: true,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 部门树选项
      deptOptions: [],
      // 显示搜索条件
      showSearch: true,
      // 状态数据字典
      statusOptions: [],
      // 总条数
      total: 0,
      // 缺陷类型表格数据
      defecttypeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        parentId: null,
        ancestors: null,
        defectName: null,
        orderNum: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        parentId: [
          { required: true, message: "上级缺陷不能为空", trigger: "blur" },
        ],
        deptName: [
          { required: true, message: "缺陷名称不能为空", trigger: "blur" },
        ],
        orderNum: [
          { required: true, message: "显示排序不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_normal_disable").then((response) => {
      this.statusOptions = response.data;
    });
  },
  methods: {
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$confirm(
        '确认要"' + text + '""' + row.defectName + '"缺陷类型吗?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return changeDefectStatus(row.defectId, row.status);
        })
        .then(() => {
          this.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.status = row.status === "0" ? "1" : "0";
        });
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.defectId,
        label: node.defectName,
        children: node.children,
      };
    },
    /** 查询缺陷类型列表 */
    getList() {
      this.loading = true;
      listInfo(this.queryParams).then((response) => {
        // this.defecttypeList = this.handleTree(response.data, "defectId");
        this.defecttypeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 字典状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        defectId: null,
        parentId: null,
        defectName: null,
        orderNum: null,
        status: "0",
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.defectId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.openDisabled = false;
      if (row != null) {
        this.form.parentId = row.defectId;
      }
      this.open = true;
      this.title = "添加缺陷类型";
      listDefecttype().then((response) => {
        this.deptOptions = this.handleTree(response.data, "defectId");
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.openDisabled = false;
      const defectId = row.defectId || this.ids;
      getDefecttype(defectId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改缺陷类型";
      });

      listDefectExcludeChild(defectId).then((response) => {
        this.deptOptions = this.handleTree(response.data, "defectId");
      });
    },
    /** 查看按钮 */
    // handleView(row) {
    //   this.reset();
    //   this.openDisabled = true;
    //   const defectId = row.defectId || this.ids;
    //   getDefecttype(defectId).then((response) => {
    //     this.form = response.data;
    //     this.open = true;
    //     this.title = "查看缺陷类型";
    //   });
    // },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.defectId != null) {
            updateDefecttype(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            const rLoading = this.openLoading();
            addDefecttype(this.form)
              .then((response) => {
                this.msgSuccess("新增成功");
                this.open = false;
                rLoading.close();
                this.getList();
              })
              .catch((error) => {
                rLoading.close();
              });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const defectIds = row.defectId || this.ids;
      this.$confirm(
        '是否确认删除缺陷类型编号为"' + defectIds + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delDefecttype(defectIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "basic/defecttype/export",
        {
          ...this.queryParams,
        },
        "缺陷类型" + this.parseTime(new Date()) + ".xlsx"
      );
    },
  },
};
</script>